import json

from django.shortcuts import render, redirect
from django.utils.decorators import method_decorator
from django.views import View
from apps.user.models import User
from utils.verifyUtil import verifyParam
from yige_shopping.settings import alipay
from utils.resFormatUtil import ResFormat
from .models import Order
from merchandise.models import MerchandiseOptions
from django.core import serializers

import uuid


# Create your views here.

class OrderView(View):
    def get(self, request):
        data = request.GET.dict()
        sign = data.pop('sign')

        # if not sign or not out_trade_no:
        #     return 错误页面

        res = alipay.verify(data, sign)
        out_trade_no = data.pop('out_trade_no')
        print(res)

        status = 2
        if res:
            status = 1
        # 5941d592-a864-47e6-bdc8-f64b2c98ebd0
        order = Order.objects.filter(order_no=out_trade_no)[0]
        order.status = status
        order.save()
        return redirect('/static/index.html')  # 建议还是跳转到订单页

    @method_decorator(verifyParam('id', 'option_id', 'subject'))
    def post(self, request):
        post = request.POST
        id = post.get('id')
        option_id = post.get('option_id')
        subject = post.get('subject')
        # dkrkxo1393@sandbox.com
        order_no = str(uuid.uuid4())  # 生成订单号

        option = MerchandiseOptions.objects.get(id=option_id, merchandise_id=id)  # 获取商品选项 ，关键选项，
        if not option:
            return ResFormat(status='PARAM_ERROR').json_response()

        user = User.objects.filter(email=request.email)[0]
        if not user:
            return ResFormat(status='PARAM_ERROR').json_response()

        Order.objects.create(order_no=order_no, money=option.price, subject=subject, merchandise_id=id, user_id=user.id)

        order_string = alipay.api_alipay_trade_page_pay(
            # 订单号，唯一的字符串信息
            out_trade_no=order_no,
            # 金额
            total_amount=option.price,
            # 商品信息
            subject=subject,
            # 回调地址
            return_url='http://one.free.idcfengye.com/order/ali_pay/'
        )

        pay_url = 'https://openapi.alipaydev.com/gateway.do?' + order_string
        # print(pay_url)
        return ResFormat(data=pay_url).json_response()


class OrderUserView(View):
    def get(self, request):
        order_list = Order.objects.filter(user__email=request.email)
        orders = json.loads(serializers.serialize("json", order_list))
        return ResFormat(data=orders).json_response()
